import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
const store=new Vuex.Store({
  state: {
    token:'',
   
    //当localStorage里面有goodsList就直接取
    //否则为空
    goodsList:JSON.parse(localStorage.getItem('goodsList'))||[],
  },
  mutations: {
      setToken(state,token){
        state.token=token;
      },
      //把要添加的项目传进来，如果存在，则加数量
      //如果不存在，就加入数组
      addCart(state,item){
        
        let goods=state.goodsList.find(e=>e.title===item);
        if(goods){
          goods.count++
        }else{
          state.goodsList.push({title:item,count:1});
        }
 
      },
     

      //购物车页减少产品数量
      subItem(state,index){
        
        
        if(state.goodsList[index].count>0){
          state.goodsList[index].count--;
        }else{
          state.goodsList[index].splice(index,1);
        }
      
        
      },
      //购物车页增加商品数量
      addItem(state,index){
        state.goodsList[index].count++;
        
      },
      cancelAll(state){
        state.goodsList=[];
      }
  },
  //异步处理
  actions: {

  },
  //相当于vue中的computed
  getters: {
    getCountNum(state){
      let count=0;
      state.goodsList.forEach(e=>{
        count+=e.count;
      })
      return  count;
    },
   
    
  }
})
// 当 store 初始化后调用
store.subscribe((mutations,state)=>{
     
  localStorage.setItem('goodsList',JSON.stringify(state.goodsList));
})
export default store